(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.popup.profFeeViewController', profFeeViewController);
	profFeeViewController.$inject = [ '$scope', '$q', '$uibModalInstance', '$timeout', '$filter', 'Constants', 'dialogsModule', 'gridService', 'modalService', 'layoutConfig' , 'authService', 'ajaxServiceFactory', 'validatorConfig', 'arithService', 'formatService', 'commonService'];
	function profFeeViewController($scope, $q, $uibModalInstance, $timeout, $filter, Constants, dialogsModule, gridService, modalService, layoutConfig, authService, ajaxServiceFactory, validatorConfig, arithService, formatService, commonService) {
		var ctrl = this, log = $scope.loggerFactory.getLogger("profFeeViewController"), ajaxService = ajaxServiceFactory.buildAjaxService({
			getProfFeeOptions : {
				url : 'do/cda/dataList/profFeeOptions',
				method : 'post'
			},
			getFeeCodeLayout : {
				url : 'do/cda/profFee/layout',
				method : 'post'
			}
		});
		ctrl.dialogsModule = dialogsModule;
		ctrl.validatorConfig = validatorConfig;
		ctrl.prodType = ctrl.dialogsModule.params.prodType;
		ctrl.prodCode = ctrl.dialogsModule.params.prodCode;
		ctrl.bigestInEvtCcy = ctrl.dialogsModule.params.bigestInEvtCcy;
		ctrl.profileType = ctrl.dialogsModule.params.profileType;
		ctrl.profileId = ctrl.dialogsModule.params.profileId;
		ctrl.filterPrimaryKeys = ctrl.dialogsModule.params.filterPrimaryKeys;
		ctrl.formName = "profFeeForm";
		ctrl.profFee = {};
		
		ctrl.init = function() {
			initSubTableDefine(layoutConfig);
			ctrl.initGeneral().then(function() {
				var initProfFee = ctrl.dialogsModule.params.profFee;
				initProfFee.oldTierType = undefined;
				initProfFee.oldTierType2 = undefined;
				initLayoutAndDataBySpreadTierType(initProfFee).then(function(){
					if (ctrl.profFeeOld) {
						ctrl.profFeeOld.tierCriterias = ctrl.profFeeOld.tierCriterias || [];
					}
					initDataByProfFee();
				});
			});
		};
		
		ctrl.initGeneral = function() {
			// for spread tier Criteria
			initTierCriteria();
			// init
			var params = {};
			params.prodType = ctrl.prodType;
			params.prodCode = $filter('encode')(ctrl.prodCode);
			var defer = $q.defer();
			getProfFeeOptions(params).then(function(response) {
				ctrl.feeTypeOptions = response.feeTypeOptions;
				ctrl.feeCcyOptions = angular.copy(response.currencyOptions);
				ctrl.feeLimitCcyOptions = response.currencyOptions;
				ctrl.amortizeMinCcyOptions = response.currencyOptions;
				ctrl.feeCalcTypeOptions = response.feeCalcTypeOptions;	
				ctrl.allFeeCalcBasisOptions = response.feeCalcBasisOptions;	
				ctrl.plusBaseRateFlagOptions = angular.copy(response.yesNoOptions);
				ctrl.allAmortizeFlagOptions = angular.copy(response.yesNoOptions);
				ctrl.amortizeFlagOptions = angular.copy(response.yesNoOptions);
				ctrl.amortEarlyFlagOptions = angular.copy(response.yesNoOptions);
				ctrl.tierCalcTypeOptions = response.tierCalcTypeOptions;
				ctrl.requiredFlagOptions = angular.copy(response.yesNoOptions);
				ctrl.privateFlagOptions = angular.copy(response.yesNoOptions);
				ctrl.allocCodeOptions = response.allocCodeOptions;
				ctrl.tierByOptions = angular.copy(response.tierByOptions);
				ctrl.tierBy2Options = angular.copy(response.tierByOptions);
				ctrl.copyTierTypeOptions = angular.copy(ctrl.tierByOptions);
				ctrl.copyTierType2Options = angular.copy(ctrl.tierBy2Options);
				ctrl.eventCodeOptions = response.eventCodeOptions;
				ctrl.ccyOptions =  angular.copy(response.currencyOptions);
				ctrl.feeCodeOptions = response.feeCodeOptions;
				defer.resolve();
			}, angular.noop);
			return defer.promise;
		};
		function getProfFeeOptions(params) {
			var defer = $q.defer();
			ajaxService.getProfFeeOptions(params).then(function(response) {
				var profFeeOptions = {};
				if (response.data) {
					angular.forEach(response.data, function(value, key) {
						var tempValue = {};
						tempValue = value;
						profFeeOptions[key] = tempValue;
					});
				}
				defer.resolve(profFeeOptions);
			});
			return defer.promise;
		}
		
		function initLayoutAndDataBySpreadTierType(initProfFee) {
			var defer = $q.defer();
			if(initProfFee.tierType && initProfFee.tierType != 'N' && initProfFee.tierType != initProfFee.oldTierType){
				initProfFee.oldTierType = initProfFee.tierType;
				initProfFee.oldTierType2 = initProfFee.tierType2;
				var params = {};
				params.action = 'profFeeView';
				params.tierType = initProfFee.tierType;
				if(initProfFee.tierType2){
					params.tierType2 = initProfFee.tierType2;
				}
				ajaxService.getFeeCodeLayout(params).then(function(response) {
					var tmp = angular.copy(initProfFee);
					// 1. change layout
					$timeout(function(){
						ctrl.layoutConfig = response.data;
					});
					// reset model after change layout
					$timeout(function(){
						ctrl.profFee = tmp;
						changeColumnDefsForTierType(ctrl, $scope, true);
						// format by new tierType
						if (ctrl.profFee.tierType && ctrl.profFee.tierType != 'N') {
							formatCriteria(ctrl);
						}
						if (ctrl.profFee.tierType2 && ctrl.profFee.tierType2 != 'N') {
							formatCriteria2(ctrl);
						}
						defer.resolve();
					});
				});
			} else {
				ctrl.layoutConfig = layoutConfig;
				ctrl.profFee = initProfFee;
				changeColumnDefsForTierType(ctrl, $scope, true);
				// format by new spreadTierType
				if (ctrl.profFee.tierType && ctrl.profFee.tierType != 'N') {
					formatCriteria(ctrl);
				}
				if (ctrl.profFee.tierType2 && ctrl.profFee.tierType2 != 'N') {
					formatCriteria2(ctrl);
				}
				defer.resolve();
			}
			return defer.promise;
		}
		
		function initDataByProfFee() {
		}
		
		ctrl.eventCodeChanged = function(value) {
			if (ctrl.profFee.eventCode && ctrl.profFee.ccy) {
				if (!ctrl.profFee.feeCodeSeq) {// update has already exist feeCodeSeq
//					var pre = ctrl.bigestInEvtCcy[ctrl.profFee.eventCode + ":" + ctrl.profFee.ccy];
					var pre = (ctrl.bigestInEvtCcy) ? ctrl.bigestInEvtCcy["big"] : null;
					if (pre) {
						ctrl.profFee.feeCodeSeq = arithService.add(pre, 1);
					} else {
						ctrl.profFee.feeCodeSeq = 1;
					}
				}
				generateReservedFeeCode(ctrl);
			}
		};
		
		ctrl.ccyChanged = function(value) {
			if (ctrl.profFee.eventCode && ctrl.profFee.ccy) {
				if (!ctrl.profFee.feeCodeSeq) {// update has already exist feeCodeSeq
//					var pre = ctrl.bigestInEvtCcy[ctrl.profFee.eventCode + ":" + ctrl.profFee.ccy];
					var pre = (ctrl.bigestInEvtCcy) ? ctrl.bigestInEvtCcy["big"] : null;
					if (pre) {
						ctrl.profFee.feeCodeSeq = arithService.add(pre, 1);
					} else {
						ctrl.profFee.feeCodeSeq = 1;
					}
				}
				generateReservedFeeCode(ctrl);
			}
		};
		
		ctrl.feeCodeChanged = function(value, form, isFirstLoad) {
			if (ctrl.profFee.feeCode) {
				for (var i = 0; i < ctrl.feeCodeOptions.length; i++) {
					var _feeCode = ctrl.feeCodeOptions[i];
					if (_feeCode.value == ctrl.profFee.feeCode) {
						ctrl.profFee.feeExtProperty = _feeCode;
						// only change feecode, give it default allocCode, but has exist data can't do it
						if (!isFirstLoad)
							ctrl.profFee.allocCode = ctrl.profFee.allocCode || ctrl.profFee.feeExtProperty.allocCode;
					}
				}
			}
		};
		
		
		ctrl.feeCcyChanged = function(value) {
		};
		
		ctrl.feeCalcBasisChanged = function(value) {
			if (ctrl.profFee.calcBase) {
				controlTierCalcType(ctrl);
			}
		};
		
		ctrl.feeTypeChanged = function(model) {
			if (ctrl.profFee.feeType) {
			//  It can be Y only when AMORTIZE_FLAG of its fee type (in FEETYPE table) is Y
				var amortizeFlagFromFeeType;
				for (var a = 0; a < ctrl.feeTypeOptions.length; a++) {
					if (ctrl.feeTypeOptions[a].value == ctrl.profFee.feeType) {
						amortizeFlagFromFeeType = ctrl.feeTypeOptions[a].extProperty.amortizeFlag;
						break;
					}
				}
				if (amortizeFlagFromFeeType == 'Y') {
					// feecode amortizeFlag can be 'Y' and 'N' to choice
					ctrl.amortizeFlagOptions = angular.copy(ctrl.allAmortizeFlagOptions);
				} else {
					// delete "Y"
					for (var i = 0; i < ctrl.amortizeFlagOptions.length; i++) {
						if (ctrl.amortizeFlagOptions[i].value == 'Y') {
							ctrl.amortizeFlagOptions.splice(i, 1);
							break;
						}
					}
					if (ctrl.profFee.amortizeFlag == 'Y') {
						ctrl.profFee.amortizeFlag = 'N';
					}
				}
			}
		}
		
		ctrl.feeCodeNameChanged = function(model) {
		}
		
		ctrl.feeCalcTypeChanged = function(value) {
			if (ctrl.profFee.feeCalcType) {
				// feeCalcBasis
				var feeCalcBasisData = [];
				for (var i = 0; i < ctrl.allFeeCalcBasisOptions.length; i++) {
					var _feeCalcBase = ctrl.allFeeCalcBasisOptions[i];
					var _filterTypes = _feeCalcBase.feeCalcType;
					if (_filterTypes && _filterTypes.indexOf(ctrl.profFee.feeCalcType) >= 0) {
						feeCalcBasisData.push(_feeCalcBase);
					}
				}
				ctrl.feeCalcBasisOptions = feeCalcBasisData;
				//default value.
				if(ctrl.profFee.feeCalcType != 'U') {
					if(!ctrl.profFee.calcBase || !commonService.isValidOption(ctrl.feeCalcBasisOptions, ctrl.profFee.calcBase)) {
						ctrl.profFee.calcBase = "A";
					}
				}
				//
				if (ctrl.profFee.feeCalcType != 'I') {
//					ctrl.profFee.plusBaseRateFlag = ctrl.profFee.plusBaseRateFlag || 'N';
					ctrl.profFee.plusBaseRateFlag = 'N';
				}
				if (!(ctrl.profFee.feeCalcType == 'P' || ctrl.profFee.feeCalcType == 'I' || ctrl.profFee.feeCalcType == 'U')) {
					delete ctrl.profFee.feeLimitCcy;
					delete ctrl.profFee.feeLimitMin;
					delete ctrl.profFee.feeLimitMax;
				}
				//
				if (!(ctrl.profFee.feeCalcType == 'F' || ctrl.profFee.feeCalcType == 'U')) {
					delete ctrl.profFee.feeCcy;
				}
				
				if (!(ctrl.profFee.feeCalcType == 'F' || ctrl.profFee.feeCalcType == 'P' || ctrl.profFee.feeCalcType == 'U')) {
					ctrl.profFee.amortizeFlag = 'N';
				}
				
				controlTierCalcType(ctrl);
				
				changeColumnDefsForTierType(ctrl, $scope, true);
			}
		};
		
		ctrl.amortizeFlagChanged = function(value) {
			if (ctrl.profFee.amortizeFlag) {
				if (ctrl.profFee.amortizeFlag != 'Y') {
					delete ctrl.profFee.amortizeMinCcy;
					delete ctrl.profFee.amortizeMinAmount;
					ctrl.profFee.amortEarlyFlag = 'N';
				}
			}
		};
		
		ctrl.privateFlagChanged = function(value) {
			if (!ctrl.profFee.privateFlag) return;
			if (ctrl.profFee.privateFlag == 'Y') {
				if (!ctrl.profFee.ccy) {
					modalService.openErrorDialogs({
						'messages' : ['js.info.proffee.ccy-need-first-select']
					});
					$timeout(function() {
						ctrl.profFee.privateFlag = 'N';
					})
					return;
				}
				if (!ctrl.profFee.eventCode) {
					modalService.openErrorDialogs({
						'messages' : ['js.info.proffee.event-need-first-select']
					});
					$timeout(function() {
						ctrl.profFee.privateFlag = 'N';
					})
					return;
				}
				generateReservedFeeCode(ctrl);
			} else {
				// hidden tier
				ctrl.profFee.tierType = 'N';
				// need clear
				ctrl.profFee.tierCriterias = [];
			}
		};
		
		/**
		 * code name is _TTnnnnnnnnnnqqq, where TT is PROFILE_TYPE, nnnnnnnnnn is the 10-digit profile id and qqq is 3-digit fee sequence FEE_CODE_SEQ
		 */
		function generateReservedFeeCode(ctrl) {
			if (ctrl.profFee.privateFlag == 'Y') {
				var profileType = ctrl.profileType;
				var profileId = replenishPrefixInteger($filter('encode')(ctrl.profileId), 10);
				var feeCodeSeq = replenishPrefixInteger(ctrl.profFee.feeCodeSeq, 3);
				if(!(ctrl.profFee.feeCode && ctrl.profFee.feeCode.indexOf("_") == 0)) {
					ctrl.profFee.feeCode = "_" + profileType + profileId + feeCodeSeq;
				}
			}
		}
		
		function replenishPrefixInteger(num, length) {
			return (Array(length).join('0') + num).slice(-length);
		}
		
		function initSubTableDefine(layoutConfig) {
			//init tierCriterias
			if(ctrl.validatorConfig && ctrl.validatorConfig.profFees) layoutConfig.formConfigs.tierCriteria.tableConfigs.table.validatorConfig = ctrl.validatorConfig.profFees.tierCriterias;
			ctrl.tierCriteriaInnerGridOptions = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.tierCriteria.tableConfigs.table, tierCriteriaRowSelectionChanged);
			ctrl.tierCriteriaInnerGridOptions.data = 'vm.profFee.tierCriterias';
			function tierCriteriaRowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedTierCriterias = selectedRows;
			}
		};
		
		/*******************Spread Tier**********************/
		function initTierCriteria() {
			ctrl.tierTypeChanged = function(value) {
				if (ctrl.profFee.tierType && ctrl.profFee.tierType != 'N') {
					// readonly and also need clear data
					ctrl.profFee.feeValueAmt = '';
					ctrl.profFee.feeValuePerc = '';
					ctrl.profFee.feeValueRate = '';
					
					//remove the tiertype
					var resultOptions = [];
					angular.forEach(ctrl.copyTierType2Options, function(obj) {
						if (obj.value != ctrl.profFee.tierType) {
							resultOptions.push(obj);
						}
					});
					ctrl.tierBy2Options = resultOptions;
				}
				
				if (ctrl.profFee.tierType == 'N') {
					ctrl.profFee.tierCalcType = 'N';
					// need clear
					ctrl.profFee.tierCriterias = [];
				}
				
				changeLayoutBySpreadTierType();
				
				controlTierCalcType(ctrl);
			};
			
			ctrl.tierType2Changed = function(value) {
				if (ctrl.profFee.tierType2 && ctrl.profFee.tierType2 != 'N') {
					//remove the tiertype
					var resultOptions = [];
					angular.forEach(ctrl.copyTierTypeOptions, function(obj) {
						if (obj.value != ctrl.profFee.tierType2) {
							resultOptions.push(obj);
						}
					});
					ctrl.tierByOptions = resultOptions;
				}
				
				var tierType2 = ctrl.profFee.tierType2;
				if (tierType2 && tierType2 != 'N') {
					// format by new tierType2
					formatCriteria2(ctrl);
					// need hidden some first column criteria
					resetHasFrontSameCriteria(ctrl);
				} else if (tierType2 == 'N') {
					// also need open hidden first column
					resetHasFrontSameCriteria(ctrl);
					// also format first column criteria, some hidden value may be error show format
					// format by new tierType
					formatCriteria(ctrl);
				}
				
				changeLayoutBySpreadTierType2();
				
				controlTierCalcType(ctrl);
			};
			
			function changeLayoutBySpreadTierType() {
				if(ctrl.profFee.tierType && ctrl.profFee.tierType != ctrl.profFee.oldTierType){
					ctrl.profFee.oldTierType = ctrl.profFee.tierType;
					var params = {};
					params.action = 'profFeeView';
					params.tierType = ctrl.profFee.tierType;
					if(ctrl.profFee.tierType2){
						params.tierType2 = ctrl.profFee.tierType2;
					}
					ajaxService.getFeeCodeLayout(params).then(function(response) {
						var tmp = angular.copy(ctrl.profFee);
						// 1. change layout
						$timeout(function(){
							ctrl.layoutConfig = response.data;
						});
						// reset model after change layout
						$timeout(function(){
							ctrl.profFee = tmp;
							changeColumnDefsForTierType(ctrl, $scope, true);
							// format by new tierType
							if (ctrl.profFee.tierType && ctrl.profFee.tierType != 'N') {
								formatCriteria(ctrl);
							}
						});
					});
				}
			}
			
			function changeLayoutBySpreadTierType2() {
				if((ctrl.profFee.tierType2 && ctrl.profFee.tierType2 != ctrl.profFee.oldTierType2)){
					ctrl.profFee.oldTierType2 = ctrl.profFee.tierType2;
					var params = {};
					params.action = 'profFeeView';
					params.tierType2 = ctrl.profFee.tierType2;
					if(ctrl.profFee.tierType){
						params.tierType = ctrl.profFee.tierType;
					}
					ajaxService.getFeeCodeLayout(params).then(function(response) {
						var tmp = angular.copy(ctrl.profFee);
						// 1. change layout
						ctrl.layoutConfig = response.data;
						// reset model after change layout
						$timeout(function(){
							ctrl.profFee = tmp;
							changeColumnDefsForTierType(ctrl, $scope, true);
							// format by new tierType
							if (ctrl.profFee.tierType2 && ctrl.profFee.tierType2 != 'N') {
								formatCriteria2(ctrl);
							}
						});
					});
				}
			}
			
			ctrl.criteriaChanged = function(currTierCriteria) {
				var tierByVal = ctrl.profFee.tierType;
				var ccy = ctrl.profFee.ccy;
				// format
				var criteria = formatTierCriteria(currTierCriteria.criteria, tierByVal, ccy);
				currTierCriteria.criteria = criteria;
				// if master, then need reset sub line
				var _selectedTierCriteriaIndex;
				angular.forEach(ctrl.profFee.tierCriterias, function(tierCriteria, index) {
					if (tierCriteria.$$hashKey == currTierCriteria.$$hashKey) {
						_selectedTierCriteriaIndex = index;
					}
				});
				if ((_selectedTierCriteriaIndex || _selectedTierCriteriaIndex == 0) && _selectedTierCriteriaIndex < ctrl.profFee.tierCriterias.length - 1) {
					for (var i = _selectedTierCriteriaIndex + 1; i < ctrl.profFee.tierCriterias.length; i++) {
						var tierCriteria = ctrl.profFee.tierCriterias[i];
						// belong to master
						if (tierCriteria.hasFrontSameCriteria == 'Y') {
							tierCriteria.criteria = criteria;
						} else {
							break;
						}
					}
				}
			};
			
			ctrl.criteria2Changed = function(currTierCriteria) {
				var tierByVal = ctrl.profFee.tierType2;
				var ccy = ctrl.profFee.ccy;
				// format
				var criteria2 = formatTierCriteria(currTierCriteria.criteria2, tierByVal, ccy);
				currTierCriteria.criteria2 = criteria2;
			};
		}
		
		function changeColumnDefsForTierType(ctrl, $scope, viewFlag) {
			if (!ctrl.profFee) return;
			if (ctrl.profFee.tierType != ctrl.profFee.tmpOldTierType 
				|| ctrl.profFee.tierType2 != ctrl.profFee.tmpOldTierType2 
				|| ctrl.profFee.feeCalcType != ctrl.profFee.tmpOldFeeCalcType ) {
				ctrl.profFee.tmpOldTierType = ctrl.profFee.tierType;
				ctrl.profFee.tmpOldTierType2 = ctrl.profFee.tierType2;
				ctrl.profFee.tmpOldFeeCalcType = ctrl.profFee.feeCalcType;
				// Amount:A U
				// other is number
				var dynamicType, dynamicFormat;
				if (ctrl.profFee.tierType == 'A') {
					dynamicType = "money";
					dynamicFormat = "vm.profFee.dynamicParams.TXN_CCY.value";
				} else if (ctrl.profFee.tierType == 'U') {
					dynamicType = "money";
					dynamicFormat = "vm.profFee.dynamicParams.ASSET_CCY.value";
				} else if (ctrl.profFee.tierType == 'C') {
					if (ctrl.profFee.dynamicParams && ctrl.profFee.dynamicParams.USE_SCORE && ctrl.profFee.dynamicParams.USE_SCORE.value && ctrl.profFee.dynamicParams.USE_SCORE.value == 'N') {
						// TODO only char, need change
						dynamicType = "number";
						dynamicFormat = "integer";
					} else {//default use_scope is 'Y'
						dynamicType = "number";
						dynamicFormat = "integer";
					}
				} else {
					// default
					dynamicType = "number";
					dynamicFormat = "integer";
				}
				var dynamicType2, dynamicFormat2;
				if (ctrl.profFee.tierType2 == 'A') {
					dynamicType2 = "money";
					dynamicFormat2 = "vm.profFee.dynamicParams.TXN_CCY.value";
				} else if (ctrl.profFee.tierType2 == 'U') {
					dynamicType2 = "money";
					dynamicFormat2 = "vm.profFee.dynamicParams.ASSET_CCY.value";
				} else if (ctrl.profFee.tierType2 == 'C') {
					if (ctrl.profFee.dynamicParams && ctrl.profFee.dynamicParams.USE_SCORE && ctrl.profFee.dynamicParams.USE_SCORE.value && ctrl.profFee.dynamicParams.USE_SCORE.value == 'N') {
						// TODO only char, need change
						dynamicType2 = "number";
						dynamicFormat2 = "integer";
					} else {//default use_scope is 'Y'
						dynamicType2 = "number";
						dynamicFormat2 = "integer";
					}
				} else {
					// default
					dynamicType2 = "number";
					dynamicFormat2 = "integer";
				}
				var dynamicType3, dynamicFormat3;
				if (ctrl.profFee.feeCalcType == 'I' || ctrl.profFee.feeCalcType == 'P') {
					dynamicType3 = "percentage";
					dynamicFormat3 = "defaultPercentage";
				} else {
					// default
					dynamicType3 = "money";
					dynamicFormat3 = "vm.profFee.feeCcy";
				}
				var columnDefs = [
                  {
                	  "label": "label.feecode.criteria",
                	  "model": "criteria",
                	  "type": dynamicType,
                	  "readonly": viewFlag,
                	  "format": dynamicFormat,
                	  "options": {
							"data": "vm.criteriaOptions",
							"callback": {
								"changed": "vm.criteriaChanged"
							}
						},
                	  "show": "row.entity.hasFrontSameCriteria == 'N'"
                  },
                  {
                	  "label": "label.feecode.criteriavalue",
                	  "model": "criteriaValue",
                	  "type": dynamicType3,
                	  "readonly": viewFlag,
                	  "format": dynamicFormat3,
                	  "options": {}
                  }
                ];
				var columnDefs2 = [
                   {
                	   "label": "label.feecode.criteria",
                	   "model": "criteria",
                	   "type": dynamicType,
                	   "format": dynamicFormat,
                	   "readonly": viewFlag,
                	   "options": {
							"data": "vm.criteriaOptions",
							"callback": {
								"changed": "vm.criteriaChanged"
							}
						},
                	   "show": "row.entity.hasFrontSameCriteria == 'N'"
                   },{
                	   "label": "label.feecode.criteria2",
                	   "model": "criteria2",
                	   "type": dynamicType2,
                	   "format": dynamicFormat2,
                	   "readonly": viewFlag,
                	   "options": {
	               			"data": "vm.criteria2Options",
	               			"callback": {
	               				"changed": "vm.criteria2Changed"
	               			}
	               		}
                   },
                   {
                	   "label": "label.feecode.criteriavalue",
                	   "model": "criteriaValue",
                	   "type": dynamicType3,
                	   "readonly": viewFlag,
                	   "format": dynamicFormat3,
                	   "options": {}
                   }
                ];
				if (ctrl.profFee.tierType2 && ctrl.profFee.tierType2 != 'N') {
					columnDefs = columnDefs2;
				}
				if(ctrl.validatorConfig && ctrl.validatorConfig.profFees) ctrl.layoutConfig.formConfigs.tierCriteria.tableConfigs.table.validatorConfig = ctrl.validatorConfig.profFees.tierCriterias;
				ctrl.layoutConfig.formConfigs.tierCriteria.tableConfigs.table.columnDefs = columnDefs;
				ctrl.tierCriteriaInnerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.tierCriteria.tableConfigs.table, tierCriteriaRowSelectionChanged);
				ctrl.tierCriteriaInnerGridOptions.data = 'vm.profFee.tierCriterias';
				ctrl.tierCriteriaInnerGridOptions.verifyData  = 'vm.profFeeOld.tierCriterias';
				function tierCriteriaRowSelectionChanged(eventRow, selectedRows) {
					ctrl.selectedTierCriterias = selectedRows;
				}
			}
		}
		
		/*function controlTierCalcType(ctrl) {
			if (ctrl.profFee.tierType != 'N' && ctrl.profFee.tierType2 != 'N') {
				ctrl.profFee.tierCalcType = 'N';
				ctrl.tierCalcTypeReadonly = true;
			} else {
				if (ctrl.profFee.feeCalcType == 'F') {
					ctrl.tierCalcTypeReadonly = false;
				} else {
					if (ctrl.profFee.tierType == ctrl.profFee.calcBase) {
						ctrl.tierCalcTypeReadonly = false;
					} else {
						ctrl.profFee.tierCalcType = 'N';
						ctrl.tierCalcTypeReadonly = true;
					}
				}
			}
		}*/
		
		function controlTierCalcType(ctrl) {
			/*if (ctrl.profFee.tierType != 'N' && ctrl.profFee.tierType2 != 'N') {
				ctrl.tierCalcTypeOptions = getTierCalcTypeOptions(false); 
			} else {
				if (ctrl.profFee.feeCalcType != 'P') {
					ctrl.tierCalcTypeOptions = getTierCalcTypeOptions(true);
				} else {
					if (ctrl.profFee.tierType == ctrl.profFee.calcBase) {
						ctrl.tierCalcTypeOptions = getTierCalcTypeOptions(true);
					} else {	
						ctrl.tierCalcTypeOptions = getTierCalcTypeOptions(false);
					}
				}
			}*/
			if (ctrl.profFee.tierType != 'N' && ctrl.profFee.tierType == 'T') {
				ctrl.tierCalcTypeOptions = getTierCalcTypeOptions(true); 
			} else {
				ctrl.tierCalcTypeOptions = getTierCalcTypeOptions(false);
			}
		}
		
		function getTierCalcTypeOptions(ifStep) {
			var option1 = [ {
				"value" : "N",
				"label" : "label.feecode.tiercalctype.none"
			},{
				"value" : "I",
				"label" : "label.feecode.tiercalctype.interpolation"
			},{
				"value" : "S",
				"label" : "label.feecode.tiercalctype.step"
			},{
				"value" : "B",
				"label" : "label.feecode.tiercalctype.single"
			},{
				"value" : "C",
				"label" : "label.feecode.tiercalctype.combo"
			},{
				"value" : "A",
				"label" : "label.feecode.tiercalctype.static"
			}];
			var option2 = [  {
				"value" : "N",
				"label" : "label.feecode.tiercalctype.none"
			},{
				"value" : "I",
				"label" : "label.feecode.tiercalctype.interpolation"
			}];
			if(ifStep){
				return option1;
			}else {
				return option2;
			}
		}
		
		function formatCriteria(ctrl) {
			var tierByVal = ctrl.profFee.tierType;
			var ccy = ctrl.profFee.ccy;
			if (ctrl.profFee.tierCriterias && ctrl.profFee.tierCriterias.length > 0) {
				for (var i = 0; i < ctrl.profFee.tierCriterias.length; i++) {
					var tierCriteria = ctrl.profFee.tierCriterias[i];
					var criteria = formatTierCriteria(tierCriteria.criteria, tierByVal, ccy);
					tierCriteria.criteria = criteria;
				}
			}
		}
		
		function formatCriteria2(ctrl) {
			var tierByVal = ctrl.profFee.tierType2;
			var ccy = ctrl.profFee.ccy;
			if (ctrl.profFee.tierCriterias && ctrl.profFee.tierCriterias.length > 0) {
				for (var i = 0; i < ctrl.profFee.tierCriterias.length; i++) {
					var tierCriteria = ctrl.profFee.tierCriterias[i];
					var criteria2 = formatTierCriteria(tierCriteria.criteria2, tierByVal, ccy);
					tierCriteria.criteria2 = criteria2;
				}
			}
		}
		
		/**
		 * format the assinged line's criteria in tier table
		 */
		function formatTierCriteria(criteria, tierByVal, ccy){
			if (!criteria || arithService.eq(criteria, 0)) return;
			var value = criteria;
			if(tierByVal == "T"){
				//LOAN TENOR need format 1,231,231
//				value = formatService.formatNumber(formatService.parseNumber(criteria), "nfmtMoney0");
				return value;
			} else if(tierByVal == "U" || tierByVal == "A" ){
				//LOAN AMOUNT need format 1,231,231.00
//				value = formatService.formatMoney(formatService.parseMoney(criteria), ccy);
				return value;
			} else {
				if(arithService.eq(criteria, 0) && criteria.length > 1) {//00...
					value = criteria = '';
				}
				if(tierByVal == "E"){//DATE
					var dateVal = criteria;
					if(arithService.gt(dateVal, 0) && !isDate(String(dateVal))){
						value = '';
					}
				} else if(tierByVal == "R"){//YEAR
					if(arithService.gt(criteria, 9999)){
						value = '';
					}
				} else if(tierByVal == "Y"){//DAY
					if(arithService.gt(criteria, 31)){
						value = '';
					}
				} else if(tierByVal == "H"){//MONTH
					if(arithService.gt(criteria, 12)){
						value = '';
					}
				} else if(tierByVal == "K"){//WEEK
					if(arithService.gt(criteria, 7)){
						value = '';
					}
				}
				//roundNum(tierCriteria.criteria, 0)
//				value = formatService.round(value, 0);
				return value;
			}
		}
		
		/**
		 * if the date is valid: 20090102, 2009-01-02, 2009/01/02
		 */
		function isDate(s){
			var r = s.match(/^(\d{1,4})(|-|\/)(\d{1,2})\2(\d{1,2})$/); 
			if(r==null)return false; 
			var d= new Date(r[1], r[3]-1, r[4]); 
			return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
		}
		
		/**
		 * reset TierCriteria for hasSameCriteria
		 * if tierType2 isnot "N", then may be hidden hasSameCriteria
		 * if tierType2 is "N", then open all hidden first columns
		 */
		function resetHasFrontSameCriteria (ctrl) {
			// need hidden some first column criteria
			if (ctrl.profFee.tierType != "N" && ctrl.profFee.tierType2 != "N") {
				if (ctrl.profFee.tierCriterias && ctrl.profFee.tierCriterias.length > 0) {
					var lastCriteria;
					for (var i = 0; i < ctrl.profFee.tierCriterias.length; i++) {
						var tierCriteria = ctrl.profFee.tierCriterias[i];
						var criteria = tierCriteria.criteria;
						if (ctrl.profFee.tierType == "T"){
							criteria = formatService.parseNumber(criteria);
						} else if(ctrl.profFee.tierType == "U" || ctrl.profFee.tierType == "A" ){
							criteria = formatService.parseMoney(criteria);
						} 
						if (i == 0) {
							lastCriteria = criteria;
							tierCriteria.hasFrontSameCriteria = "N";
							continue;
						}
						//
						if (lastCriteria && arithService.eq(criteria, lastCriteria)) {
							tierCriteria.hasFrontSameCriteria = "Y";
						} else {
							tierCriteria.hasFrontSameCriteria = "N";
						}
						lastCriteria = criteria;
					}
				}
			} 
			// also need open hidden first column
			else if (ctrl.profFee.tierType != "N" && ctrl.profFee.tierType2 == "N") {
				if (ctrl.profFee.tierCriterias && ctrl.profFee.tierCriterias.length > 0) {
					for (var i = 0; i < ctrl.profFee.tierCriterias.length; i++) {
						var tierCriteria = ctrl.profFee.tierCriterias[i];
						tierCriteria.hasFrontSameCriteria = "N";
					}
				}
			}
		}
		/*******************Spread Tier**********************/
		
		ctrl.close = function() {
			if (!dialogsModule.btnCallback || !dialogsModule.btnCallback['close'] || dialogsModule.btnCallback['close']() !== false) {
				$uibModalInstance.dismiss();
			}
		};
		
	}
})(angular);
